<!--  -->
<script setup>
import { voteAPI } from '@/apis/vote'
import { ref } from 'vue'
import Tip from '@/components/tip'
import { us } from '@/utils/userState'

const props = defineProps(['initCnt', 'initStatus', 'userId', 'objectId', 'objectType'])

const cnt = ref(props.initCnt)
const active = ref(props.initStatus)


function doAgree() {
  const type = active.value == 2 ? 1 : active.value == 1 ? 0 : 1
  voteAPI(us.value.loggedUseId, props.userId, props.objectId, props.objectType, type, active.value)
    .then(() => {
      if (props.initStatus == 2) active.value = type == 1 ? type : props.initStatus
      else active.value = type
      if (props.initStatus == 1) cnt.value = type == 1 ? props.initCnt : props.initCnt - 1
      else if (props.initStatus == 2) cnt.value = type == 1 ? props.initCnt + 2 : props.initCnt
      else cnt.value = type == 1 ? props.initCnt + 1 : props.initCnt
    })
    .catch(() => Tip.error('投票失败'))
}

function doDisagree() {
  const type = active.value == 1 ? 2 : active.value == 2 ? 0 : 2
  console.log(type, active.value)

  voteAPI(us.value.loggedUseId, props.userId, props.objectId, props.objectType, type, active.value)
    .then(() => {
      if (props.initStatus == 1) active.value = type == 2 ? type : props.initStatus
      else active.value = type
      if (props.initStatus == 1) cnt.value = type == 2 ? props.initCnt - 2 : props.initCnt
      else if (props.initStatus == 2) cnt.value = type == 2 ? props.initCnt : props.initCnt + 1
      else cnt.value = type == 2 ? props.initCnt - 1 : props.initCnt
    })
    .catch(() => Tip.error('投票失败'))
}

</script>

<template>
  <div class="op-container">
    <div class="icon-wrapper" :class="{ 'active': active === 1 }" @click="doAgree">
      <Icon icon-name="thumb" />
    </div>
    <div class="cnt">{{ cnt }}</div>
    <div class="icon-wrapper" :class="{ 'active': active === 2 }" @click="doDisagree">
      <Icon icon-name="thumb" class="flipY" />
    </div>
  </div>
</template>

<style scoped lang="scss">
.op-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  border: 1px solid var(--border-secondary);
  border-radius: 3px;
  background-color: #f1f7ec;

  .cnt {
    padding: 0 10px;
    border-left: 1px solid var(--border-secondary);
    border-right: 1px solid var(--border-secondary);
  }

  .icon-wrapper {
    cursor: pointer;
    transition: all .1s ease-out;
    padding: 5px;

    .icon {
      background-color: #9bbd7f;
      transition: background-color .1s ease-out;
    }

    &:hover,
    &:focus {

      .icon {
        background-color: rgb(169, 114, 87);
      }
    }
  }

  .active {

    .icon {
      background-color: rgb(0, 147, 10) !important;
    }
  }
}

.icon {
  vertical-align: middle;
  width: 18px;
  height: 18px;
}
</style>
